<!-- 
 * 新增需求
 * @author: 冯宇
 * @since: 2022-05-16
 * index.vue
-->
<template>
  <div class="add-invest-container detailsPageBox">
    <div class="detailsMain">
      <div class="need-title">
        <div class="icon"></div>
        <div>机构图标</div>
      </div>

      <div class="header-img" @click="uploadImg">
        <img :src="data.imgSrc" v-show="data.imgSrc" />
        <input type="file" style="display: none" ref="headImg" @change="chooseImg" :multiple="false" />
        <div class="button" v-show="!data.imgSrc">
          <span class="icon">+</span>
          <span>添加图片</span>
        </div>
      </div>

      <div class="need-title need-title-2">
        <div class="icon"></div>
        <div>基本信息</div>
      </div>

      <el-form :inline="true" :model="data.form" label-width="70px" :rules="data.rules">
        <el-form-item label="机构名称：" class="message" prop="organizationName">
          <el-input v-model="data.form.organizationName" @mouseleave="getCompanyEID"></el-input>
        </el-form-item>
        <el-form-item label="经营状况：" class="message" prop="status">
          <el-input v-model="data.form.status" disabled></el-input>
        </el-form-item>
        <el-form-item label="注册资金：" class="message" prop="regist_capi">
          <el-input v-model="data.form.regist_capi" disabled></el-input>
        </el-form-item>
        <el-form-item label="统一编码：" class="message" prop="credit_no">
          <el-input v-model="data.form.credit_no" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系人：" class="message">
          <el-input v-model="data.form.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系方式：" class="message">
          <el-input v-model="data.form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="所在地：">
          <ChooseAddress width="70%" @changeAddress="changeAddress" :back-info="data.address" :show-detail-address="true" direction="right"></ChooseAddress>
        </el-form-item>
      </el-form>

      <div class="need-title need-title-2">
        <div class="icon"></div>
        <div>主投技术领域</div>
      </div>
      <div>
        <el-tag closable class="tag" v-for="(ind1, i) in data.industrySelected" @close="removeTag(i)">{{ ind1.keyName }}</el-tag>
      </div>
      <el-select style="margin-top: 10px" placeholder="请选择主要技术领域" @change="addIndustry">
        <el-option v-for="ind in data.industrySelectList" :label="ind.keyName" :value="ind.keyId" />
      </el-select>

      <div class="need-title need-title-2">
        <div class="icon"></div>
        <div>机构简介</div>
      </div>
      <!-- <el-input type="textarea" :rows="5" v-model="data.textArea" resize="none" placeholder="请填写机构简介"></el-input> -->
          <TextEditor @textEdit="textEdit" :type="0" :html="data.textArea"></TextEditor>

      <div class="need-title need-title-2">
        <div class="icon"></div>
        <div>投资事件</div>
      </div>

      <div style="margin-bottom: 10px">
        <el-button type="success" @click="data.visible = true">新增投资事件</el-button>
      </div>

      <TableCom :tableHeader="data.tableHeader" :tableData="data.tableData" :isShowCheckbox="false" handleWidth="100" :loading="false" :showPage="false" :isShowLogicHandleCol="true" :isShowTableBtn="false" :isShowGrooveHandleCol="false" :isShowIndex="false">
        <template #handle="scope">
          <div class="table-handle" @click="delTable(scope.row)">删除</div>
        </template>
      </TableCom>

      <el-form :model="data" class="need-title-2">
        <el-form-item label="是否启用：">
          <el-radio-group v-model="data.valid">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <div class="send-btn detailsHandBtn">
      <el-button type="primary" style="width: 100px; height: 36px" @click="send">提交</el-button>
      <el-button style="width: 100px; height: 36px">取消</el-button>
    </div>

    <el-dialog v-model="data.visible" width="30%">
      <template #title>
        <div class="need-title">新增投资事件</div>
      </template>
      <template #default>
        <el-form :data="data.addForm" label-width="80px" ref="addDom">
          <el-form-item label="投资公司：" prop="name">
            <el-input v-model="data.addForm.name" placeholder="请填写投资公司" @blur="searchEID" />
          </el-form-item>
          <el-form-item label="投资时间：" prop="date">
            <el-date-picker v-model="data.addForm.date" type="date" value-format="YYYY-MM-DD" placeholder="请选择投资时间" />
          </el-form-item>
          <el-form-item label="投资类型：" prop="text">
            <el-select v-model="data.addForm.text">
              <el-option label="领投" value="领投" />
              <el-option label="跟投" value="跟投" />
            </el-select>
          </el-form-item>
          <el-form-item label="投资轮次：" prop="round">
            <el-select v-model="data.addForm.round">
              <el-option :label="round.keyName" :value="round.keyName" v-for="round in data.roundSelectList" />
            </el-select>
          </el-form-item>
          <el-form-item label="投资金额：" prop="amount">
            <el-input v-model="data.addForm.amount" placeholder="请填写投资金额（万元）" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="addEvent">添加</el-button>
        <el-button @click="cancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { onMounted, reactive, onUnmounted, ref, computed, nextTick } from 'vue'
import { getCompanyEidByOrganizationNameApi, getCompanyLogoByEidApi, companyLogoUploadApi } from '@/api/interface/scientific.js'
import { getCompanyDetailApi, addOrganizationApi, organizationDetailApi } from '@/api/interface/investOrganization.js'

import { getDictListApi, getDictItemListApi } from '@/api/public/publicDict.js'

import { ElMessage, ElMessageBox } from 'element-plus'
import { backRoute } from '@/utils/common.js'

import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
const store = useStore()
const router = useRouter()
const route = useRoute()

const headImg = ref(null)
const addDom = ref(null)

const data = reactive({
  imgSrc: '',
  eid: '',
  form: {
    organizationName: '',
    status: '',
    regist_capi: '',
    credit_no: '',
    contact: '',
    mobile: '',
  },
  rules: {
    organizationName: {
      required: true,
      validator: (rule, value, callback) => {
        if (/^[\u4e00-\u9fa5]{1,30}$/.test(value) == false) {
          callback(new Error('请输入正确的公司名称'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
    status: { required: true },
    regist_capi: { required: true },
    credit_no: { required: true },
  },
  address: {
    provinceName: '',
    provinceCode: '',
    cityName: '',
    cityCode: '',
    areaName: '',
    areaCode: '',
    detailAddress: '',
  },
  addForm: {
    amount: '',
    date: '',
    name: '',
    round: '',
    text: '',
    eid: '',
  },
  visible: false,

  industrySelected: [],
  industrySelectList: [],
  textArea: '',
  roundSelectList: [],
  tableHeader: [
    {
      label: '投资公司',
      prop: 'name',
    },
    {
      label: '投资时间',
      prop: 'date',
    },
    {
      label: '投资类型',
      prop: 'text',
    },
    {
      label: '投资轮次',
      prop: 'round',
    },
    {
      label: '投资金额',
      prop: 'amount',
    },
  ],
  tableData: [],
  valid: true,
})

onMounted(() => {
  const level = router.currentRoute.value.meta.level
  store.dispatch('setting/setRouterCut', level)
})
onUnmounted(() => {
  store.dispatch('setting/setRouterCut', 2)
})

//根据机构名称=>eid，根据eid=>logo
const getCompanyEID = async () => {
  // if (!data.form.organizationName) return
  if(!/^[\u4e00-\u9fa5]{1,30}$/.test(data.form.organizationName)) return
  const eid = await getCompanyEidByOrganizationNameApi({ name: data.form.organizationName.trim() }).then((res) => {
    if (res.status === 200) {
      data.eid = res.data
      return res.data
    }
  })
  await getCompanyLogoByEidApi({ eid }).then((res) => {
    if (res.status === 200) {
      data.imgSrc = res.data
    }
  })
  getCompanyDetailApi({ ipi: 1, ips: 10, companyName: data.form.organizationName }).then((res) => {
    if (res.status === 200) {
      data.form.status = res.data.result[0].status
      data.form.regist_capi = res.data.result[0].regist_capi
      data.form.credit_no = res.data.result[0].credit_no

      const a = res.data.result[0].provinceName
      const b = res.data.result[0].cityName
      const c = res.data.result[0].areaName
      let d = res.data.result[0].detailAddress

      data.address.provinceName = a
      data.address.provinceCode = res.data.result[0].provinceCode
      data.address.cityName = b
      data.address.cityCode = res.data.result[0].cityCode
      data.address.areaName = c
      data.address.areaCode = res.data.result[0].areaCode
      data.address.detailAddress = d.replace(a, '').replace(b, '').replace(c, '')
    }
  })
}
//获取主投技术领域
const getDictList = async () => {
  const dict = {
    ipi: 1,
    ips: 20,
    keyName: '',
  }
  const dictList = await getDictListApi(dict).then((res) => {
    if (res.status === 200) {
      return res.data.result
    }
  })
  dictList.forEach((v) => {
    if (v.keyId === 'DICT_INDUSTRY') {
      let a = {
        dictType: v.keyId,
      }
      getDictItemListApi(JSON.stringify(a)).then((res) => {
        data.industrySelectList = res.data.result
      })
    } else if (v.keyId === 'DICT_ROUND_DISTRIBUTION') {
      let a = {
        dictType: v.keyId,
      }
      getDictItemListApi(JSON.stringify(a)).then((res) => {
        data.roundSelectList = res.data.result
      })
    }
  })
}
getDictList()
//选择技术领域
const addIndustry = (val) => {
  data.industrySelectList.forEach((v) => {
    if (v.keyId == val && !data.industrySelected.find((vv) => vv.keyId == v.keyId)) {
      data.industrySelected.push(v)
    }
  })
}
//移除领域
const removeTag = (i) => {
  data.industrySelected.splice(i, 1)
}

//点击选择图片
const uploadImg = () => {
  headImg.value.click()
}
//选择图片上传
const chooseImg = (e) => {
  const file = e.target.files[0]
  let fd = new FormData()
  fd.append('file', file)
  fd.append('eid', data.eid)
  companyLogoUploadApi(fd).then((res) => {
    if (res.status === 200) {
      data.imgSrc = URL.createObjectURL(file)
    }
  })
}
//地址
const changeAddress = (info) => {
  data.address = info
}
//添加投资事件
const addEvent = () => {
  let a = {
    amount: data.addForm.amount,
    date: data.addForm.date,
    name: data.addForm.name,
    round: data.addForm.round,
    text: data.addForm.text,
    eid: data.addForm.eid,
  }
  data.tableData.push(a)
  cancel()
}
//取消添加
const cancel = () => {
  data.addForm.amount = ''
  data.addForm.date = ''
  data.addForm.name = ''
  data.addForm.round = ''
  data.addForm.text = ''
  data.addForm.eid = ''
  data.visible = false
}
const searchEID = () => {
  if (!data.addForm.name) return
  getCompanyEidByOrganizationNameApi({ name: data.addForm.name.trim() }).then((res) => {
    if (res.status === 200) {
      data.addForm.eid = res.data
    }
  })
}
//删除table一行
const delTable = (row) => {
  data.tableData.forEach((v, i) => {
    if (v.name == row.name) {
      data.tableData.splice(i, 1)
    }
  })
}



//富文本
const textEdit = (text, type) => {
  if (type === 0) {
    data.textArea = text
  }
}

//提交
const send = () => {
  const params = {
    areaCode: data.address.areaCode,
    areaName: data.address.areaName,
    brief: data.textArea,
    cityCode: data.address.cityCode,
    cityName: data.address.cityName,
    contactPerson: data.form.contact,
    contact: data.form.mobile,
    detailAddress: data.address.detailAddress,
    eid: data.eid, //非必传
    event: data.tableData, //非必传
    industry_distribution_l1: data.industrySelected.map((v) => ({ code: v.keyId, name: v.keyName })), //非必传
    name: data.form.organizationName.trim(),
    provinceCode: data.address.provinceCode,
    provinceName: data.address.provinceName,
    valid: data.valid,
    status: data.form.status,
    regist_capi_new: +data.form.regist_capi.replace(/[\u4E00-\u9FA5]/g, ''),
    credit_no: data.form.credit_no,
  }
  addOrganizationApi(JSON.stringify(params)).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: res.message,
        type: 'success',
      })
      backRoute('InvestOrganization')
    }
  })
}
</script>

<style lang="scss" scoped>
.el-select-dropdown__list {
  .el-select-dropdown__item {
    font-size: 12px;
  }
}

.add-invest-container {
  padding: 20px;

  .header-img {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 120px;
    height: 120px;
    // background-color: #f5f5f5;
    border-radius: 4px;
    border: 1px solid #f0f0f0;
    overflow: hidden;
    cursor: pointer;

    img {
      width: 100%;
    }

    .button {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 14px;

      .icon {
        font-size: 40px;
      }
    }
  }

  .need-title {
    display: flex;
    padding-bottom: 20px;
    font-size: 16px;
    font-weight: 700;

    .icon {
      width: 6px;
      height: 16px;
      background: #00a2ff;
      margin-right: 6px;
    }
  }

  .need-title-2 {
    margin-top: 20px;
  }

  .message {
    width: 32%;
  }

  :deep(.el-textarea__inner) {
    padding: 10px;
    font-size: 12px;
  }

  .tag {
    height: 32px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .table-handle {
    text-align: center;
    width: 100%;
    color: #f74b33;
    cursor: pointer;
  }
  :deep(.table-container) {
    padding: 0;
  }
  .analysis {
    display: flex;
    position: relative;

    .choose {
      position: absolute;
      right: 20px;
      top: 46px;
      padding: 20px;
      width: 50%;
      max-height: 400px;
      overflow-y: scroll;
      background: #ffffff;
      box-shadow: 0px 0px 30px 0px rgba(164, 171, 201, 0.5);
      border-radius: 8px;
      box-sizing: border-box;
      z-index: 99;

      .title {
        font-size: 18px;
        font-weight: 700;
      }

      .table {
        margin: 20px 0;
      }

      .button {
        text-align: right;
      }
    }
  }

  .send-btn {
    text-align: center;
  }
}

::v-deep .el-form-item__label {
  font-size: 12px;
  padding-right: 0;
}
</style>